package oss.ngocminh.fw;

import java.util.regex.Pattern;

import oss.ngocminh.fw.data.Post;
import android.content.Context;
import android.text.Html;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

public class PostView extends LinearLayout {
	
	private static final Pattern VIEW_POST_PATTERN = Pattern.compile(
			"<a [^>]+>.*?<img [^>]+alt=\"View Post\"[^>]+>.*?</a>", 
			Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
	private static final int HIGHLIGHTED_COLOR = 0xffffb2ff;
	private static final int NORMAL_COLOR = 0x000000ff;
	
	private boolean read;
	private StateChangeListener stateChangeListener;
	private Post post;
	private View.OnTouchListener touchListener = new View.OnTouchListener() {
		
		@Override
		public boolean onTouch(View v, MotionEvent event) {
			setRead(true);
			return true;
		}
	};

	public PostView(Context context) {
		super(context);
	}
	
	public PostView(Context context, Post post) {
		super(context);
		init(post);
	}

	public PostView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public void init(Post post) {
		setPost(post);
		setOrientation(LinearLayout.VERTICAL);
		setPadding(10, 0, 0, 0);
		setRead(false);
		
    	TextView txtUserName = new TextView(getContext());
    	txtUserName.setText(post.getUserName());
    	txtUserName.setOnTouchListener(touchListener);
    	addView(txtUserName);
    	
		TextView txtMessage = new TextView(getContext());
		txtMessage.setLayoutParams(new LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
		txtMessage.setMovementMethod(LinkMovementMethod.getInstance());
    	txtMessage.setText(convertMessage(post.getContent()));
    	txtMessage.setOnTouchListener(touchListener);
    	addView(txtMessage);
	}

	private Spanned convertMessage(String html) {
		html = VIEW_POST_PATTERN.matcher(html).replaceAll("");
		return Html.fromHtml(html);
	}

	public boolean isRead() {
		return read;
	}

	public void setRead(boolean read) {
		if (this.read != read) {
			this.read = read;
			setBackgroundColor(read ? NORMAL_COLOR : HIGHLIGHTED_COLOR);
			if (stateChangeListener != null) {
				stateChangeListener.onReadChange(this);
			}
		}
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		setRead(true);
		return super.onTouchEvent(event);
	}
	
	public StateChangeListener getStateChangeListener() {
		return stateChangeListener;
	}

	public void setStateChangeListener(StateChangeListener stateChangeListener) {
		this.stateChangeListener = stateChangeListener;
	}

	public Post getPost() {
		return post;
	}

	public void setPost(Post post) {
		this.post = post;
	}

	public interface StateChangeListener {
		
		void onReadChange(PostView postView);
		
	}

}
